// pages/search/index.js
const app = getApp();
var url = getApp().globalData.ApiUrl;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list:['商品','店铺'],
    searchKey: '',
    slist: [],      // 历史记录
    goods_list: [],   // 商品列表
    store_list: [],   // 店铺列表
    showList: true,
    kong: false,
    hasList: false,
    showStore: false,
    detailData: '', //商品详情具体数据
    goods_storage: '',  //商品库存
    goods_price: '', //商品价格
    specALLArr: [],  //商品规格名称
    propertyChildNames: '', //已选中的商品
    buyGoods_id: '', //购物车要传的商品id
    showView: false,
    num: 1,
    goods_img: '',
    imgUrl: '',
    currentTab: 0, //默认选择第一个
    nogoods: false, //搜索商品缺省
    nostore: false, //搜索店铺缺省
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    // this.getGoodsList(options);
    that.getGoodsList(that.data.searchKey);
    // this.openHistorySearch();
  },
  openHistorySearch: function () {
    var that = this;
    // this.setData({
    //   slist: wx.getStorageSync('slist',this.data.searchKey) || [],//若无储存则为空
    // })
    if (that.slist!=0) {
      that.setData({
        show: true,
      });
    }
  },
  // 删除
  delTap: function() {
    var that = this;
    wx.clearStorageSync('slist', that.data.searchKey)
    that.setData({
      slist: [],
      show: false
    })
  },
  selTap: function(e) {
    var that = this;
    var current = e.currentTarget.dataset.index;
    if (current == 0) {
      that.getGoodsList(that.data.searchKey);
    }
    if (current == 1) {
      that.getSearch();
    }
    that.setData({
      currentTab: e.currentTarget.dataset.index
    })
  },
  // 搜索
  searchForm: function(e) {
    var that = this;
    var value = e.detail.value;
    var search = that.data.slist;
    that.setData({
      searchKey: value,
    });
    var currentTab = that.data.currentTab;
    if(currentTab == 0){
      that.getGoodsList(e.detail.value);
    }else{
      that.getSearch(e.detail.value);
    }
  },
  // 搜索店铺
  getSearch(res) {   
    var that = this;
    var data = {};
    if (that.data.searchKey){
      data['keyword'] = that.data.searchKey
    }
    wx.showLoading({
      title: '加载中...',
    });
    wx.request({
      url: url + '/mobile/index.php?act=store&op=store_search',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'GET',
      data: {
        keyword: that.data.searchKey,
      },
      success: (res) => {
        wx.hideLoading();
        if (res.data.datas.length == 0) {
          that.setData({
            store_list: [],
            showStore: false,
            nostore: true,
          });
        }else{
          that.setData({
            nostore: false,
          });
        }
        that.setData({
          store_list: res.data.datas,
          showList: false,
          hasList: false,
          showStore: true
        })
      }
    })
  },
  // 商品搜索
  getGoodsList: function(e) {  
    var that = this;  
    wx.showLoading({
      title: '加载中...',
    });
    wx.request({
      url: url + '/mobile/index.php?act=goods&op=goods_list',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'GET',
      data: {
        key: 3,
        order: 1,
        keyword: e,
      },
      success: (res) => {
        if (res.data.code == 200) {
          wx.hideLoading();
          if (res.data.datas.goods_list.length == 0){
            that.setData({
              nogoods: true,
            });
          }else{
            that.setData({
              nogoods: false,
            });
          }
          that.setData({
            goods_list: res.data.datas.goods_list,
            showList: false,
            hasList: true,
            showStore: false
          });
        } else {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
        }
      },
      fail: () => {
        wx.showToast({
          title: '人太多啦',
          icon: 'none'
        });
      }
    });
  },
  // 加入购物车--展开弹窗
  addToCar: function (e) {
    var that = this;
    var that = this;
    var dataset = e.currentTarget.dataset;
    var img = e.currentTarget.dataset.goods_img;
    var mobile = wx.getStorageSync("mobile");
    if (!mobile) {
      wx.navigateTo({
        url: '/pages/index/index',
      })
    }
    that.setData({
      goods_img: img
    });
    that.getDetails(dataset);
  },
  /**
   * 获取商品详情
   */
  getDetails: function (dataset) {
    var that = this;
    wx.request({
      url: url + '/mobile/index.php?act=goods&op=goods_detail',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'GET',
      data: {
        goods_id: dataset.goods_id
      },
      success: (res) => {
        if (res.data.code == 200) {
          var datas = res.data.datas;
          var specObj = res.data.datas.goods_info.spec_name;
          var tmp = {}; //商品规格
          var tmp2 = {}; //商品尺寸
          var specALLArr = []; // 商品贵和和商品
          for (var i in specObj) {
            tmp.id = i;
            tmp.name = specObj[i];
            tmp.twoData = [];
            for (var j in res.data.datas.goods_info.spec_value[i]) {
              tmp2.id = j;
              tmp2.name = res.data.datas.goods_info.spec_value[i][j];
              tmp2.propertyID = i;
              tmp.twoData.push(JSON.parse(JSON.stringify(tmp2)));

            }
            specALLArr.push(JSON.parse(JSON.stringify(tmp)));
          };
          that.setData({
            specALLArr: specALLArr,
            detailData: datas,  //商品详情
            buyGoods_id: dataset.goods_id, //购买的商品价格
            goods_price: dataset.goods_price, //商品价格
            goods_storage: datas.goods_info.goods_storage, //商品库存
            showView: true
          });
        } else {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
        }
      },
      fail: ()=> {
        wx.showToast({
          title: '人太多啦',
          icon: 'none',
          duration: 1500,
        })
      }
    });
  },
  /**
   * 加入购物车--提交购买
   * @author chelfinn
   * @date 2018-09-19
   */

  addInCar: function (e) {
    var that = this;
    var name = this.data.propertyChildNames.split(" ");
    if (this.data.specALLArr.length == 0) {
      if (this.data.goods_storage == 0) {
        wx.showModal({
          title: '提示',
          content: '库存不足，请购买其他商品~',
          showCancel: false
        });
        return false;
      };
    } else {
      if (this.data.goods_storage == 0) {
        wx.showModal({
          title: '提示',
          content: '库存不足，请购买其他商品~',
          showCancel: false
        });
        return false;
      };
      if (name.length != this.data.specALLArr.length) {
        wx.showModal({
          title: '提示',
          content: '请先选择商品规格和尺寸~',
          showCancel: false,
        });
        return false;
      }
    }
    wx.request({
      url: url + '/mobile/index.php?act=member_cart&op=cart_add',
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      dataType: 'json',
      method: 'POST',
      data: {
        key: wx.getStorageSync('key'),
        goods_id: e.currentTarget.dataset.goods_id,
        quantity: e.currentTarget.dataset.quantity
      },
      success: (res) => {
        if (res.data.code == 200) {
          wx.showToast({
            title: '加入购物车成功',
            icon: 'success',
            duration: 2000
          });
          this.setData({
            showView: false,
            propertyChildNames: '',
          });
        } else {
          if (res.data.login == 0 && res.data.login) {
            wx.navigateTo({
              url: '/pages/authorize/index',
            })
          } else {
            wx.showToast({
              title: res.data.datas.error,
              icon: 'none',
              duration: 1500,
              mask: true
            })
          };
          this.setData({
            showView: false,
            propertyChildNames: '',
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '人太多啦',
          icon: 'none',
          duration: 1500
        })
      }
    });
  },
  errorTap: function () {
    this.setData({
      showView: false,
      propertyChildNames: '',
    });
  },
  //点击减号
  minuAcvive: function () {
    var num = this.data.num;
    if (num > 1) {    //如果num大于1才能减
      num--;
    };
    // 只有大于一件的时候，才能normal状态，否则disable状态
    var minusStatus = num <= 1 ? 'disabled' : 'normal';
    // 将数值与状态写回
    this.setData({
      num: num,
      minusStatus: minusStatus
    });
  },
  // 点击加号 
  addActive: function () {
    var num = this.data.num;
    num++;
    // 只有大于一件的时候，才能normal状态，否则disable状态
    var minusStatus = num < 1 ? 'disabled' : 'normal';
    // 将数值与状态写回
    this.setData({
      num: num,
      minusStatus: minusStatus
    });
  },
  toGoodsDetailsTap: (e) => {
    wx.navigateTo({
      url: '/pages/group-detail/index?goods_id=' + e.currentTarget.dataset.goods_id,
    })
  },
  toStore: (e) => {
    wx.navigateTo({
      url: '/pages/store/home/index?store_id=' + e.currentTarget.dataset.store_id,
    })
  },
  toGoodsList: (e) => {
    wx.navigateTo({
      url: '/pages/goods-list/index?goods_id=' + e.currentTarget.dataset.goods_id,
    })
  },
  // 扫码
  toScanCode: function (e) {
    wx.switchTab({
      url: '/pages/trace/index',
    })
  }
})